package com.trainingcloud.action.document;

import java.io.InputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.trainingcloud.action.BaseSessionAction;
import com.trainingcloud.dao.DocumentDAO;
import com.trainingcloud.dao.HistoryDAO;
import com.trainingcloud.entity.Document;
import com.trainingcloud.exception.DAOException;
import com.trainingcloud.exception.SystemException;

public class DownloadAction extends BaseSessionAction
{
	private int documentId;
	private String contentType;
	private String filename;
	private InputStream fileStream;
	
	public DownloadAction() throws SystemException 
	{
		super();
	}
	
	@Override
	public String callWithSession() throws DAOException, SystemException 
	{
		DocumentDAO documentDAO = new DocumentDAO();
		Document document = documentDAO.getDocumentById(documentId);
		if(document==null)
		{
			return "Invalid document id.";
		}
		
		HistoryDAO historyDAO = new HistoryDAO();
		historyDAO.logHistory(currentUser.getId(), document.getId(), new Date());
		
		filename = document.getFilename();
		contentType = document.getMimeType();
		fileStream = ServletActionContext.getServletContext().getResourceAsStream("/documents/"+document.getFileLocation());
		
		return NO_XML_RESPONSE;
	}
	
	public InputStream getDownloadFile() throws Exception
	{
		return fileStream;
	}
	
	public String getContentType() {
		return contentType;
	}
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	public int getDocumentId() {
		return documentId;
	}
	public void setDocumentId(int documentId) {
		this.documentId = documentId;
	}

}
